﻿using System;
using DecisionMaking.BusinessLogic;
using DecisionMaking.BusinessLogic.Model;
using MvcContrib;
using System.Web.Mvc;

namespace DecisionMaking.WebApp.Controllers
{
    [HandleError]
    [Authorize]
    public class CandidatesController : BaseController
    {
        /// <summary>
        /// Injected by Windsor 
        /// </summary>
        public IEnvironmentManager EnvironmentManager { private get; set; }	

        [HttpGet]
        public ActionResult List(int id)
        {
            var environment = EnvironmentManager.GetEnvironment(id);

            // make sure current user is owner of current environment
            if (!environment.Account.Equals(CurrentAccount))
            {
                return AccessDenied();
            }

            ViewData["environment"] = environment;
            var candidates = EnvironmentManager.GetCandidates(id);

            return View(candidates);
        }

        [HttpGet]
        public ActionResult Add(int id)
        {
            var environment = EnvironmentManager.GetEnvironment(id);

            // make sure current user is owner of current environment
            if (!environment.Account.Equals(CurrentAccount))
            {
                return AccessDenied();
            }

            ViewData["environment"] = environment;

            var model = new CandidateModel {EnvironmentId = id};
            model.InitCues(EnvironmentManager.GetCues(id));

            return View("Edit", model);
        }

        [HttpPost]
        public ActionResult Add(CandidateModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var candidate = EnvironmentManager.SaveCandidate(model);
                    // go to list
                    return this.RedirectToAction(c => c.List(candidate.Environment.Id));
                }
                catch (DuplicateCandidateNameException e)
                {
                    ModelState.AddModelError("Name", "A candidate with this name already exists");

                }
            }

            ViewData["environment"] = EnvironmentManager.GetEnvironment(model.EnvironmentId.GetValueOrDefault());

            return View("Edit", model);            
        }

        [HttpGet]
        public ActionResult Edit(int id)
        {
            try
            {
                var candidate = EnvironmentManager.GetCandidate(id);

                // make sure current user is owner of current candidate
                if (!candidate.Environment.Account.Equals(CurrentAccount))
                {
                    return AccessDenied();
                }

                ViewData["environment"] = candidate.Environment;

                var model = new CandidateModel
                {
                    EnvironmentId = candidate.Environment.Id,
                    CandidateId = candidate.Id,
                    Name = candidate.Name,
                    IndependentVariableValue = candidate.IndependentVariableValue,
                };

                foreach (var cueValue in candidate.CueValues)
                {
                    model.CueValues.Add(new CandidateCueValueModel
                    {
                        CueId = cueValue.Cue.Id,
                        Name = cueValue.Cue.Name,
                        Value = cueValue.Value
                    });    
                }

                return View(model);
            }
            catch (EntityNotFoundException e)
            {
                return NotFound(e);
            }
        }

        [HttpPost]
        public ActionResult Edit(CandidateModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var candidate = EnvironmentManager.SaveCandidate(model);
                    // go to list
                    return this.RedirectToAction(c => c.List(candidate.Environment.Id));
                }
                catch (DuplicateCandidateNameException e)
                {
                    ModelState.AddModelError("Name", "A candidate with this name already exists");
                }
                catch (AccessDeniedException e)
                {
                    return AccessDenied(e);
                }
                catch (EntityNotFoundException e)
                {
                    return NotFound(e);
                }
            }

            // reload environment before going back to view
            ViewData["environment"] = EnvironmentManager.GetEnvironment(model.EnvironmentId.GetValueOrDefault());

            return View(model);
        }	

        [HttpPost]
        public ActionResult Delete(int id)
        {
            var candidate = EnvironmentManager.GetCandidate(id);

            // make sure current user is owner of current candidate
            if (!candidate.Environment.Account.Equals(CurrentAccount))
            {
                return AccessDenied();
            }

            EnvironmentManager.RemoveCandidate(id);

            return Json(new { success = true, deletedId = id });
        }

    }
}
